package com.ccepc.algmanage.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccepc.algmanage.service.DeployInfoService;
import com.ccepc.algmanage.utils.ApiRequestUtils;
import com.ccepc.algmanage.utils.AuthInfoUtils;
import com.ccepc.algmanage.utils.CommonUtils;
import com.ccepc.common.core.util.R;
import com.ccepc.common.log.annotation.SysLog;
import com.ccepc.demo.api.entity.ApiData;
import com.ccepc.demo.api.entity.DeployInfo;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;


/**
 *
 *
 * @author pigx code generator
 * @date 2023-11-09 10:52:14
 */
@RestController
@RequestMapping("/deployinfo" )
@Api(value = "deployinfo", tags = "部署信息")
public class DeployInfoController {

    @Resource
    private DeployInfoService deployInfoService;

    private static final String ALG_IMG_TEST = "/upload";

    private static final String ALG_VIDEO_UPLOAD = "/async_upload";

    private static final String ALG_VIDEO_TEST = "/async_result";

    @ApiOperation(value = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_view')" )
    public R getDeployInfoPage(Page<DeployInfo> page, DeployInfo deployInfo) {
        return R.ok(deployInfoService.page(page, new LambdaQueryWrapper<DeployInfo>()
                .eq(DeployInfo::getAlgorimId, deployInfo.getAlgorimId())
                .eq(deployInfo.getServerId()!=null, DeployInfo::getServerId, deployInfo.getServerId())
                .eq(deployInfo.getDeployType()!=null, DeployInfo::getDeployType, deployInfo.getDeployType())
                .eq(DeployInfo::getTenantId, AuthInfoUtils.getTenantId())
                .like(!deployInfo.getInterfaceAddr().isEmpty(), DeployInfo::getInterfaceAddr, deployInfo.getInterfaceAddr()))
        );
    }

    @ApiOperation(value = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_view')" )
    public R getById(@PathVariable("id" ) Integer id) {
        return R.ok(deployInfoService.getById(id));
    }

    @ApiOperation(value = "通过算法id查询记录条数")
    @GetMapping("/count/{algorimId}" )
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_view')" )
    public R getCountByAlgId(@PathVariable("algorimId" ) Integer algorimId) {
        return deployInfoService.alloCount(algorimId);
    }

    @ApiOperation(value = "新增或修改")
    @SysLog("新增或修改" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_add')" )
    public R save(@RequestBody DeployInfo deployInfo) {
        return deployInfoService.saveOrUpdateDepl(deployInfo);
    }

    @ApiOperation(value = "修改下发状态")
    @SysLog("新增或修改" )
    @PutMapping("/status")
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_add')" )
    public R status(@RequestBody DeployInfo deployInfo) {
        return R.ok(deployInfoService.update(
                        new LambdaUpdateWrapper<DeployInfo>()
                                .eq(DeployInfo::getId, deployInfo.getId())
                                .set(DeployInfo::getPushStatus, deployInfo.getPushStatus())
                                .set(DeployInfo::getUpdatedTime, LocalDateTime.now())
                                .set(DeployInfo::getUpdatedBy, AuthInfoUtils.getUserId())
                )
        );
    }

    @ApiOperation(value = "批量修改")
    @SysLog("批量修改" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_edit')" )
    public R updateBatch(@RequestBody List<DeployInfo> deployInfoList) {
        return R.ok(deployInfoService.updateBatchById(deployInfoList));
    }


    @ApiOperation(value = "通过id列表删除")
    @SysLog("通过id列表删除" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_del')" )
    public R removeById(@RequestBody List<DeployInfo> deployInfoList) {
        return R.ok(deployInfoService.removeBatch(deployInfoList));
    }

    @ApiOperation(value = "测试算法")
    @SysLog("测试算法" )
    @PostMapping("/upload")
    @PreAuthorize("@pms.hasPermission('algmanage_deployinfo_add')" )
    public ResponseEntity<Object> test(
            @RequestParam("name") String name,
            @RequestPart("file") MultipartFile file,
            @RequestParam("url") String url
    ) throws IOException {
        // 组装请求参数
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("file", new HttpEntity<>(file.getBytes(), createFileHeaders(file)));
        if (CommonUtils.isImageFile(name)) {
            // 发送POST请求
            requestBody.add("name", name);
            String uploadUrl = "http://" + url + ALG_IMG_TEST;
            return ApiRequestUtils.postFormData(uploadUrl, requestBody);
        } else if (CommonUtils.isVideoFile(name)){
            // 视频上传
            String uploadUrl = "http://" + url + ALG_VIDEO_UPLOAD;
            ResponseEntity<Object> entity = ApiRequestUtils.postFormData(uploadUrl, requestBody);
            JsonNode bodyNode = CommonUtils.objectToJsonNode(entity.getBody());
            if ("200".equals(bodyNode.path("status").asText())) {
                // 获取识别结果
                String resGetUrl = "http://" + url + ALG_VIDEO_TEST;
                return  ApiRequestUtils.postFormData(resGetUrl, new LinkedMultiValueMap<>());
            } else {
                return ResponseEntity.ok(R.failed("视频上传失败"));
            }
        } else {
            return ResponseEntity.ok(R.failed("文件格式出错"));
        }
    }

    private HttpHeaders createFileHeaders(MultipartFile file) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("file", file.getOriginalFilename());
        return headers;
    }

}
